package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.GoodsBean;
import com.project.mapper.IGoodsMapper;
import com.project.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class GoodsServiceImpl implements IGoodsService {
    @Autowired
    private IGoodsMapper goodsMapper;

    @Override
    public Page<GoodsBean> findByItem(Integer pageNum, String goodsName, String goodsType, String goodsStatus) {
        QueryWrapper<GoodsBean> qw = new QueryWrapper<>();
        if (goodsStatus != null && !goodsStatus.equals("")){
            qw.eq("g_status",goodsStatus);
        }
        if (goodsName != null && !goodsName.equals("")){
            qw.like("g_name",goodsName);
        }
        if (goodsType != null && !goodsType.equals("")){
            qw.like("g_type",goodsType);
        }

        return goodsMapper.selectPage(new Page<>(pageNum,3),qw);
    }

    @Override
    public void updateStatusToShow(Integer goodsId) {
        QueryWrapper<GoodsBean> qw = new QueryWrapper<>();
        qw.eq("pk_goodsId",goodsId);
        List<GoodsBean> goodsBeanList = goodsMapper.selectList(qw);
        for (GoodsBean goodsBean:goodsBeanList) {
            goodsBean.setStatus("已上架");
            goodsMapper.updateById(goodsBean);
        }
    }

    @Override
    public void add(GoodsBean goodsBean) {
        goodsMapper.insert(goodsBean);

    }

    @Override
    public void updateNum(Integer goodsId, Integer deltaNum) {//deltaNum正值可以在退货入库时调用，负值是出库时调用
        QueryWrapper<GoodsBean> qw = new QueryWrapper<>();
        qw.eq("pk_goodsId",goodsId);
        List<GoodsBean> goodsBeanList = goodsMapper.selectList(qw);
        int num = Math.abs(deltaNum);//取绝对值，即代表要出库的数量
        for (GoodsBean goodsBean:goodsBeanList
             ) {
            if (num>0 && goodsBean.getNum()>0){//这一批次需要出货
                if (goodsBean.getNum()<num){//这一批货不够
                    num = num - goodsBean.getNum();//先把这批货全发出去，需要发货数就减少了
                    goodsBean.setNum(0);
                    goodsMapper.updateById(goodsBean);
                }else {//这一批货已经够了
                    goodsBean.setNum(goodsBean.getNum()-num);
                    num = 0;
                    goodsMapper.updateById(goodsBean);
                }
            }
        }
    }
}
